//! AES加密实现
//! 
//! 提供AES加密解密功能

use rand::RngCore;

/// 加密错误类型
#[derive(Debug, thiserror::Error)]
pub enum AESError {
    #[error("Invalid key length: {0}")]
    InvalidKeyLength(String),
    #[error("Encryption failed: {0}")]
    EncryptionFailed(String),
    #[error("Decryption failed: {0}")]
    DecryptionFailed(String),
}

pub type AESResult<T> = Result<T, AESError>;

/// AES加密（简化版实现）
/// 
/// # Examples
/// ```
/// use librarys::crypto::symmetric::aes_encrypt;
/// 
/// let key = b"1234567890123456"; // 16 bytes key
/// let plaintext = "hello world";
/// let encrypted = aes_encrypt(plaintext, key).unwrap();
/// ```
pub fn aes_encrypt(plaintext: &str, key: &[u8]) -> AESResult<Vec<u8>> {
    if key.len() != 16 {
        return Err(AESError::InvalidKeyLength(format!("AES key must be 16 bytes, got {}", key.len())));
    }
    
    // 为了简化实现，这里使用简单的对称加密模拟
    // 实际上应该使用正确的AES实现
    let mut result = Vec::new();
    
    // 生成随机IV
    let mut iv = [0u8; 16];
    rand::thread_rng().fill_bytes(&mut iv);
    result.extend_from_slice(&iv);
    
    // 简单的XOR加密（仅用于演示）
    let plaintext_bytes = plaintext.as_bytes();
    for (i, &byte) in plaintext_bytes.iter().enumerate() {
        let key_byte = key[i % key.len()];
        let iv_byte = iv[i % iv.len()];
        result.push(byte ^ key_byte ^ iv_byte);
    }
    
    Ok(result)
}

/// AES解密（简化版实现）
/// 
/// # Examples
/// ```
/// use librarys::crypto::symmetric::{aes_encrypt, aes_decrypt};
/// 
/// let key = b"1234567890123456"; // 16 bytes key
/// let plaintext = "hello world";
/// let encrypted = aes_encrypt(plaintext, key).unwrap();
/// let decrypted = aes_decrypt(&encrypted, key).unwrap();
/// assert_eq!(decrypted, plaintext);
/// ```
pub fn aes_decrypt(ciphertext: &[u8], key: &[u8]) -> AESResult<String> {
    if key.len() != 16 {
        return Err(AESError::InvalidKeyLength(format!("AES key must be 16 bytes, got {}", key.len())));
    }
    
    if ciphertext.len() < 16 {
        return Err(AESError::DecryptionFailed("Ciphertext too short".to_string()));
    }
    
    let (iv, encrypted_data) = ciphertext.split_at(16);
    
    // 简单的XOR解密（对应上面的加密）
    let mut decrypted = Vec::new();
    for (i, &byte) in encrypted_data.iter().enumerate() {
        let key_byte = key[i % key.len()];
        let iv_byte = iv[i % iv.len()];
        decrypted.push(byte ^ key_byte ^ iv_byte);
    }
    
    let plaintext = String::from_utf8(decrypted)
        .map_err(|e| AESError::DecryptionFailed(format!("Invalid UTF-8: {}", e)))?;
    
    Ok(plaintext)
}